/**
 * 政企宽带预约列表
 */
(function($){
  var pageData = {};
  var pageCount = 1;
  var storeId = getParamValue("storeId");//orgId
  var userId = getParamValue("userId");
  var bd_type = getParamValue("bd_type");//宽带类型 0 爱家小区、1 优家小区、2 商务动力、3 校园套餐
  /*
  封装参数
  */
  var getMyParams = function(){
    var idVal = $("#broadband-id").val();
    var nameVal = $("#broadband-name").html();


    var params = "?";
    var myParam = getParams();
    if(myParam){
      params += myParam;
      if(idVal || nameVal){
        params += "&";
      }
    }
    if(idVal){
      params += "id=" + idVal;
      if(nameVal){
        params += "&";
      }
    }
    if(nameVal){
      params += "name=" + encodeURIComponent(nameVal);
    }

    return params;
  };
  /*
  绑定事件
  */
  var bindEvent = function(){
  	$("#broadband-list > li").off("click");//取消li事件
    /*li事件*/
  	$("#broadband-list > li").on("click",function(){
      var $siblingsNode = $(this).siblings();
      var primaryClass = "select-item";
      var defaultColor = "#fff";
      var selectColor = "#0c79b1";
      var $id = $("#broadband-id");
      var $name = $("#broadband-name");

      if($siblingsNode.hasClass(primaryClass)){
      	$siblingsNode.removeClass(primaryClass);
        $siblingsNode.css("background-color",defaultColor);
      }
      if($(this).hasClass(primaryClass)){
        $(this).removeClass(primaryClass);
        $(this).css("background-color",defaultColor);
      	$id.val("");
      	$name.html("");
      }else{
        $(this).addClass(primaryClass);
        $(this).css("background-color",selectColor);
      	$id.val($(this).find("input[name='id']").val());
      	$name.html($(this).find("div[name='name']").html());
      }
    });
    /*详情按钮*/
  	$("#broadband-list > li").find(".am-badge").on("click",function(event){
      var $id = $("#broadband-id");
      var $name = $("#broadband-name");

      var idVal = $(this).parent().find("input[name='id']").val();
      var nameVal = $(this).parent().find("div[name='name']").html();
      $id.val(idVal);
      $name.html(nameVal);

  	  window.location.href = "broadband_detail.html" + getMyParams();
  	  event.stopPropagation();
  	});
  };
  /*
  显示数据
  */
  var showDatas = function(data){
  	var $tpl = $('#amz-tpl');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var myData = {
    	list: data.list,
    	"error":"没有宽带列表信息"
    };

    var html = template(myData);
    $tpl.before(html);

    bindEvent();
  };

  var getReqParams = function(pageNumber){
    var params = {};
    params.pageNumber = pageNumber;
    params.pageSize = 10;
    params.storeId = storeId;
    params.bd_type = bd_type;

    return params;
  };

  /*
  加载数据
  */
  var loadDatas = function(pageNumber){
  	$('#modal').modal('open');
    //var params = getReqParams(pageNumber);//v1
    var params = {"pageNumber":pageNumber,"pageSize":10,"storeId":storeId,"userId":userId,"bd_type":bd_type};
    console.log("params = "+JSON.stringify(params));
  	console.log("url = "+Constants.apiV2Host + "h5/broadband/reservation/listByType");
  	$.ajax({
      //type:"post",//v1
	    //url: "../broadbandH5/listByType",//v1
      url: Constants.apiV2Host + "h5/broadband/reservation/listByType",
	    data: params,
	    dataType: "json",
	    headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        if (data.list instanceof Array) {
          data.list.sort(function(m, n) {
            return m.order_num - n.order_num;
          });
        }
	    	$('#modal').modal('close');
        $(".am-topbar").removeClass("am-hide");
	    	pageData = data;
	      console.info(data);
	      showDatas(data);
	    },
	    error : function(textStatus) {
	    	$('#modal').modal('close');
        $(".am-topbar").addClass("am-hide");
	      alert("服务器请求失败，请联系管理员！");
	      console.info("request error");
	    }
	  });
  };
  /**
  *判断分享出去的userId是否还有效
  **/
  var isValidUser = function(){
    $.ajax({
      type: "post",
      url: "../broadbandH5/isValidUser",
      data: {"userId":getParamValue("userId")},
      dataType: "json",
      headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
        //console.log(data);
        if(data == "1"){
          $(".am-topbar").removeClass("am-hide");
          loadDatas(1);
        }else{
          $(".am-topbar").addClass("am-hide");
          alert("店员信息已过期");
        }
      },
      error : function(textStatus) {
        $(".am-topbar").addClass("am-hide");
        alert("服务器请求失败，请联系管理员！");
        console.info("request error");
      }
    });
  };
  $(function(){
    console.log("broad_type = " + getParamValue("bd_type"));
    console.log("宽带套餐列表");
    /*滚动条*/
    var $doc = $(document);
    $doc.scroll(function(){
      //console.log("height = "+($doc.height() - $(window).height()));
      //console.log("scrollTop = "+Math.ceil($doc.scrollTop()));

      if(Math.ceil($doc.scrollTop()) >= ($doc.height() - $(window).height())){
        var $msg = $("#no-data-msg");
        if(!$.isEmptyObject(pageData) && (pageCount < pageData.totalPage)){
          if(!$msg.hasClass("am-hide")){
            $msg.addClass("am-hide");
          }
          loadDatas(pageData.pageNumber + 1);
          pageCount += 1;
        }else{
          if($msg.hasClass("am-hide")){
            $msg.removeClass("am-hide");
          }
        }
      }
    });
    /*预约按钮*/
    $("#broadband-reservation-btn").on("click",function(){
      //var idVal = $("#broadband-id").val();
      //var nameVal = $("#broadband-name").html();

      if(!$("#broadband-id").val() || !$("#broadband-name").html()){
        alert("请选择宽带套餐!");
      }else{
        if(bd_type == 3){//校园宽带预约
          window.location.href = "campus/broadband_reservation.html" + getMyParams();
        }else if(bd_type == 2){//商务动力宽带预约
          //window.location.href = "goventerprise/broadband_reservation.html" + getMyParams();
          console.log("dzg://kdyy" + getMyParams());
          window.location.href = "dzg://kdyy" + getMyParams();
        }else{//大市场宽带预约
          window.location.href = "broadband_reservation.html" + getMyParams();
        }
      }
    });

    
    //分享后的页面需要判断店员信息是否还有效
    if(getParamValue("saleType") == 2){
      isValidUser();
    }else{
      /*加载模态窗口*/
      var options = {closeViaDimmer: false};
      $('#modal').modal(options);
      loadDatas(1);
    }
  });
})(jQuery);
